//
//  SEGUhomeBluetoothDoorManager.m
//  ExcellentHome
//
//  Created by 揭婧雯 on 2017/7/10.
//  Copyright © 2017年 陈区. All rights reserved.
//

#import "SEGUhomeBluetoothDoorManager.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "SerialGATT.h"

@interface SEGUhomeBluetoothDoorManager () <BTSmartSensorDelegate>

@property (nonatomic, strong) SerialGATT* sensor; //优家园蓝牙
@property (nonatomic, strong) NSDictionary* blueToothDict; /**< 接收服务器数据 */
@property (nonatomic, assign) BOOL isOpeningDoorFinsished; //是否已经开门完成，防止两次开门成功回调

@property (nonatomic, copy) dispatch_block_t doorHandleCallback;

@end

@implementation SEGUhomeBluetoothDoorManager

- (void)openDoor
{
    self.isOpeningDoorFinsished = NO;
    
    // 延迟10s处理门禁超时
    WeakSelf;
    self.doorHandleCallback = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, ^{
        [weakSelf seg_timeOutAction];
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), self.doorHandleCallback);
    
    self.sensor = [[SerialGATT alloc] init];
    self.sensor.delegate = self;
    self.blueToothDict = @{@"ssid": ValueToString(self.doorModel.ssid), @"deviceid":ValueToString(self.doorModel.deviceid)};
    //[self seg_setBlueTeeth:self.blueToothDict];
    [self.sensor setup:self.blueToothDict];
}

#pragma mark - BTSmartSensorDelegate 优家园蓝牙代理
- (void)peripheralFound:(CBPeripheral*)peripheral
{
    SEGLog(@"已经找到蓝牙设备！！！！！！！！！！");
    
    [self.peripheralManager setDelegate:nil];
    self.peripheralManager = nil;
    
    self.sensor.activePeripheral = peripheral;
    [self.sensor connect:peripheral];
}

- (void)serialGATTCharValueUpdated:(NSString*)UUID value:(NSData*)data
{
    SEGLog(@"serialGATTCharValueUpdated=======>>>>>>%@", _blueToothDict);
    [self seg_afterOpenDoorSuccess];
}

- (void)beginOpenDoor {
    SEGLog(@"beginOpenDoor");
//    if (self.delegate && [self.delegate respondsToSelector:@selector(managerBeginOpenDoorAction)]) {
//        [self.delegate managerBeginOpenDoorAction];
//    }
}

- (void)openDoorSucceed {
    SEGLog(@"openDoorSucceed");
    [self seg_afterOpenDoorSuccess];
}

//- (void)openDoorFailed {
//    SEGLog(@"openDoorFaile");
//    if (self.isOpeningDoorFinsished) {
//        return;
//    }
//    self.isOpeningDoorFinsished = YES;
//    [self seg_deallocValues];
//    if (self.delegate && [self.delegate respondsToSelector:@selector(managerOpenDoorFailedWithMessage:)]) {
//        [self.delegate managerOpenDoorFailedWithMessage:kOpenDoorMessage_Failed];
//    }
//}

#pragma mark - 私有方法
//- (void)seg_setBlueTeeth:(NSDictionary*)dict
//{
//    [self.sensor setup:dict];
//
//    if (self.peripheralManager) {
//        [self.peripheralManager setDelegate:nil];
//        self.peripheralManager = nil;
//    }
//    self.peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
//}

- (void)seg_afterOpenDoorSuccess
{
    SEGLog(@"seg_afterOpenDoorSuccess");
    if (self.isOpeningDoorFinsished) {
        return;
    }
    self.isOpeningDoorFinsished = YES;
    [self seg_deallocValues];

    if (self.delegateSubject) {
        [self.delegateSubject sendNext:nil];
        [self.delegateSubject sendCompleted];
    }
    if (self.doorHandleCallback) {
        dispatch_block_cancel(self.doorHandleCallback);
        self.doorHandleCallback = nil;
    }
}

- (void)seg_timeOutAction
{
    SEGLog(@"seg_timeOutAction");
    if (self.isOpeningDoorFinsished) {
        return;
    }
    self.isOpeningDoorFinsished = YES;
    [self seg_deallocValues];
    
    if (self.delegateSubject) {
        NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:SEGOpenDoorErrorType_OpenBluetoothDoorFail userInfo:@{NSLocalizedDescriptionKey:kOpenDoorMessage_Failed}];
        [self.delegateSubject sendError:error];
    }
}

//销毁变量
- (void)seg_deallocValues
{
    SEGLog(@"seg_deallocValues");
    if (self && self.sensor) {
        // !!!:  Wendy，2018.1.10, 解决iOS11提示开门成功，门没有开问题
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.sensor dissetup];
            [self.sensor disconnect:self.sensor.activePeripheral];
        });
        self.sensor.delegate = nil;
    }
    if (self.peripheralManager) {
        self.peripheralManager = nil;
    }
}

//#pragma mark - CBPeripheralManagerDelegate
//- (void)peripheralManagerDidUpdateState:(CBPeripheralManager*)peripheral
//{
//    switch (peripheral.state) {
//            //蓝牙开启且可用
//        case CBPeripheralManagerStatePoweredOn:
//        {
//            SEGLog(@"now we are searching device...\n");
//            [self.sensor findBLKSoftPeripherals:2];
//            break;
//        }
//        default:
//            break;
//    }
//}

@end
